package com.atguigu.daijia.map.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.map.service.MapService;
import com.atguigu.daijia.model.form.map.CalculateDrivingLineForm;
import com.atguigu.daijia.model.vo.map.DrivingLineVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class MapServiceImpl implements MapService {
    @Resource
    private RestTemplate restTemplate;
    @Value("${cos.map.key}")
    private String key;

    /**
     * 计算驾驶线路
     */
    @Override
    public DrivingLineVo calculateDrivingLine(CalculateDrivingLineForm
                                                      calculateDrivingLineForm) {
        //请求腾讯提供接口，按照接口要求传递相关参数，返回需要结果
        String url = "https://apis.map.qq.com/ws/direction/v1/driving/?from={from}&to={to}&key={key}";

        Map<String, Object> map = new HashMap<>();
        String from = calculateDrivingLineForm.getStartPointLatitude() + "," + calculateDrivingLineForm.getStartPointLongitude();
        map.put("from", from); //起点
        String to = calculateDrivingLineForm.getEndPointLatitude() + "," + calculateDrivingLineForm.getEndPointLongitude();
        map.put("to", to); //终点
        map.put("key", key);

        JSONObject jsonObject = restTemplate.getForObject(url, JSONObject.class, map);

        int status = jsonObject.getIntValue("status");
        if (status != 0) {
            log.error("地图服务调用失败：{}", jsonObject);
            throw new GuiguException(ResultCodeEnum.MAP_FAIL);
        }
        JSONObject route = jsonObject.getJSONObject("result").getJSONArray("routes").getJSONObject(0);

        DrivingLineVo vo = new DrivingLineVo();
        vo.setDistance(route.getBigDecimal("distance").divide(new BigDecimal(1000), 2, RoundingMode.HALF_UP));
        vo.setDuration(route.getBigDecimal("duration"));
        vo.setPolyline(route.getJSONArray("polyline"));
        return vo;
    }
}
